<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>添加商品</title>
    <meta name="description" content="添加商品">
    <meta name="keywords" content="添加商品">

    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>

<body class="hold-transition">
    
    <div id="app">
        <div class="app-container">
          <div class="box">
            <!-- <div class="titInfo">{{titInfo}}</div> -->
            <div class="main">
                <template>
                  <div class="activePublic ">
                    <el-steps :space="200" :active="step"  finish-status="success">
                      <el-step icon="none" class="iconStep1" style="flex-basis: 33%">
                        <div slot='title'>
                            <!-- <h2>第1步</h2> -->
                            <p>选择商品分类</p>
                            <span class="stepImg"><img src="../img/stepN.jpg"></span>
                            
                        </div>
                        
                      </el-step>
                    
                      <el-step icon="none" class="iconStep2" style="flex-basis: 33%">
                        <div slot='title'>
                          <!-- <h2>第2步</h2> -->
                          <p>填写商品信息</p>
                          <span class="stepImg"><img src="../img/stepN.jpg"></span>
                        </div>
                      </el-step>
                      <el-step icon="none" class="iconStep3" style="flex-basis: 33%">
                        <div slot='title'>
                          <!-- <h2>第3步</h2> -->
                          <p>填写商品属性</p>
                        </div>
                      </el-step>
                    </el-steps>
                    <!-- 第一步 选择商品分类-->
                      <div class="basicInfo" v-show='step1'>
                        <h3 class="goodTit"><i></i>选择分类</h3>
                        <template>
                          <div>
                            <el-form>
                            <el-form-item class="tranfList">
                              <!-- 一级分类 -->
                              <transf-item :title-id="0" v-if="handleclassType.length>0" :district-list="classaData" @check-district="handleclassType"></transf-item>
                              <span class="tranicon"></span>
                              <!-- 二级分类 -->
                              <transf-item :title-id="1" v-show='twoShow' ref="twoType" :district-list="twoData" @check-district="handleTwoType"></transf-item>
                              <span class="tranicon traniconR" v-show="twoShow"></span>
                              <!-- 三级分类 -->
                              <transf-item :title-id="2" v-show='threeShow' ref="threeType" :district-list="threeData" @check-district="handleThreeType"></transf-item>
                            </el-form-item>
                            <div class="seleInfo">您当前选择的商品类别是：{{firstInfo.name}}{{twoInfo.name}}{{threeInfo.name}}</div>
                          </el-form>
                          </div>
                        </template>
                        
                      </div>
                      <!-- end -->
                      <!-- 第二步 选择商品信息-->
                      <div class="basicInfo" v-show='step2'>
                        <template>
                          <h3 class="goodTit"><i></i>基本信息</h3>
                          <el-form :model="goods.spu" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"  style="width:60%">
                            <el-form-item label="商品分类">
                              {{firstInfo.name}}{{twoInfo.name}}{{threeInfo.name}}<span class="btnEdit" @click='handleEdit'>编辑分类</span>
                            </el-form-item>
                            <el-form-item label="商品名称" prop="name">
                              <el-input v-model="goods.spu.name"></el-input>
                            </el-form-item>
                            <el-form-item label="副标题" prop="caption">
                              <el-input v-model="goods.spu.caption"></el-input>
                            </el-form-item>
                            <el-form-item label="商品品牌" prop="brandId">
                              <el-select v-model="goods.spu.brandId"  filterable placeholder="请选择品牌">
                                <el-option v-for="item in brandData" :label="item.name" :value="item.id">{{item.name}}</el-option>
                              </el-select>
                              <p class="infoTip">如果您不输入商品货号，系统将自动生成一个唯一的货号。</p>
                            </el-form-item>
                            <el-form-item label="模板" prop="freightId">
                              <el-select v-model="goods.spu.freightId" filterable placeholder="请选择模板" @change="handleChange">
                                <el-option v-for="item in templateData"  :label="item.name":value="item.id" :key="item.id"></el-option>
                              </el-select>
                            </el-form-item>
                            <h3 class="goodTit"><i></i>库存规格</h3>
                            <el-form-item label="商品货号" prop="sn">
                              <el-input v-model="goods.spu.sn"></el-input>
                            </el-form-item>
                            <el-form-item label="服务保证">
                              <el-checkbox-group v-model="goods.spu.saleService">
                                <el-checkbox v-for="item in serverData" :label="item.name" :value="item.id" :key="item.id"></el-checkbox>
                              </el-checkbox-group>
                            </el-form-item>
                          </el-form>
                        </template>
                      </div>
                      <!-- end -->
                      <!-- 第三步 选择商品属性-->
                      <div class="basicInfo" v-show='step3'>
                          <template>
                            <el-form :model="goods.spu" label-width="100px" class="demo-ruleForm">
                              <h3 class="goodTit"><i></i>商品属性</h3>
                              <el-form-item label="规格参数组">
                                  <!-- <el-input v-model="goods.spu.freight_name" class="inputW"></el-input> -->
                                  <el-select v-model="goods.spu.freightId" disabled>
                                    <el-option v-for="item in templateData"  :label="item.name":value="item.id" :key="item.id"></el-option>
                                  </el-select>
                              </el-form-item>
                              <el-form-item>
                                <span> 商品规格</span>
                                <div class="specList">
                                  <ul>
                                    <li v-for="(item,index) in properties" v-on:mouseenter="dataDetails(index)">
                                      <span >{{item.name}}：</span>
                                      <label v-for="(value,num) in item.options">
                                          <el-checkbox-group v-model="item.selectedValues">
                                              <el-checkbox :label="value" :value="value" name="type"class="checkbox check_item">{{value}}</el-checkbox><span @click="handleDel(item.id,num)" class="delInfo">删除</span>
                                          </el-checkbox-group>
                                      </label>
                                      <span v-if="index == ishow">
                                        <el-input v-model="item.value" :key="index" :value='index'>{{index}}</el-input>
                                        <el-button type="primary" @click="handleAdd(item.value,item.id)">添加</el-button>
                                      </span>
                                    </li>
                                  </ul>
                                </div>
                              <div class="tableList" v-if="tableDate.length">
                                <el-table
                                    :data="tableDate"
                                    border
                                    style="width: 100%">
                                    <div v-for="(item, index) in proper" :key="item.name" v-if="item.selectedValues.length>0">
                                        <el-table-column width="150"  :label="item.name" fixed>
                                            <template slot-scope="scope">
                                              <span>
                                                {{scope.row.options[index].name}}
                                                </span>
                                            </template>
                                        </el-table-column>
                                    </div>
                                    <el-table-column width="150" label="价格">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.price" class="w50" v-if="scope.row.status==1" disabled ></el-input>
                                            <el-input v-else v-model="scope.row.price" class="w50" @input.native="handleNumber"></el-input>
                                        </template>
                                    </el-table-column>

                                    <el-table-column width="150" label="库存数量">
                                        <template slot-scope="scope">
                                             <el-input v-model="scope.row.num" class="w50" v-if="scope.row.status==1" disabled></el-input>
                                             <el-input v-else v-model="scope.row.num" class="w50" @input.native="handleNumber"></el-input>
                                        </template>
                                    </el-table-column>

                                    <el-table-column width="150" label="库存预警值">
                                      <template slot-scope="scope">
                                           <el-input v-model="scope.row.alertNum" class="w50"  v-if="scope.row.status==1" disabled></el-input>
                                           <el-input v-else v-model="scope.row.alertNum" class="w50" @input.native="handleNumber"></el-input>
                                      </template>
                                    </el-table-column>
                                    <el-table-column width="150" label="SKU编号">
                                      <template slot-scope="scope">
                                        <el-input v-model="scope.row.spuId"  class="w50" name="test" v-if="scope.row.status==1" disabled></el-input>
                                        <el-input v-else v-model="scope.row.spuId"  class="w50" name="test"></el-input>
                                      </template>
                                  </el-table-column>
                                  <el-table-column width="150" label="重量">
                                    <template slot-scope="scope">
                                      <el-input v-model="scope.row.weight"  class="w50" name="test" v-if="scope.row.status==1" disabled></el-input>
                                      <el-input v-else v-model="scope.row.weight"  class="w50" name="test" @input.native="handleNumber"></el-input>
                                    </template>
                                    
                                  </el-table-column>
                                    <el-table-column width="150" label="是否启用">
                                        <template slot-scope="scope">
                                             <el-checkbox v-model="scope.row.status" true-label="1" false-label="0"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column width="150" label="操作">
                                        <template slot-scope="scope">
                                             <el-button type="primary" size="mini" @click="handleUpdate(scope.$index,scope.row)">上传图片</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <!-- 上传图片弹层 -->
                                <el-dialog
                                title="上传图片"
                                :visible.sync="upVisible"
                                width="30%"
                                center>

                                <el-form ref="form" :model="photoInfo" label-width="120px">
                                    <el-form-item label="商品名称：">
                                        <span>{{nameInfo}}</span>
                                    </el-form-item>
                                    <el-form-item v-for="item in upPhotoData">
                                        <span slot="label">{{item.PropertyName}}：</span>
                                        <span>{{item.name}}</span>
                                    </el-form-item>
                                    <el-form-item label="属性图片：">
                                        <el-button size="small" type="primary" @click="photoSelect('0')">图库选择</el-button>
                                        <el-upload
                                        class="upload-demo"
                                        ref="upload"
                                        :action="apiUrl+'/upload/native.do'"
                                        :on-success="handleFileSuccess" 
                                        :show-upload-list="false">
                                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                                        
                                      </el-upload>
                                      <div class="el-upload__tip">只能上传jpg/png格式文件，建议大小：25px*25px</div>
                                    </el-form-item>
                                    <el-form-item label="特殊资源：">
                                      <el-radio-group v-model="photoInfo.select">
                                        <el-radio :label="1">是</el-radio>
                                        <el-radio :label="2">否</el-radio>
                                      </el-radio-group>
                                    </el-form-item>
                                  </el-form>
                                <span slot="footer" class="dialog-footer">
                                  <el-button @click="upVisible = false">取 消</el-button>
                                  <el-button type="primary" @click="handleUpPhoto">确 定</el-button>
                                </span>
                              </el-dialog>
                               <!-- end -->
                               
                               <!-- end -->
                              </div>
                              </el-form-item>
                              <h3 class="goodTit"><i></i>商品参数</h3>
                              <div style="margin-left:100px;">
                                <el-table
                                  :data="paraItems"
                                  border
                                  style="width: 100%">
                                  <el-table-column
                                    prop="name"
                                    label="参数类型"
                                    width="180"
                                    align="right"
                                    >
                                    
                                  </el-table-column>
                                  <el-table-column
                                    label="录入参数">
                                    <template scope="scope">
                                      <el-select filterable v-model="paraItems[scope.$index].city" @change="handlePara(scope.row)" placeholder="请选择">
                                        <el-option
                                          v-for="value in scope.row.options"
                                          :key="value"
                                          :label="value"
                                          :value="value"
                                          >
                                          {{value}}
                                        </el-option>
                                      </el-select>
                                    </template>
                                  </el-table-column>
                                </el-table>
                              </div>
                              <h3 class="goodTit"><i></i>商品相册</h3>
                              <div style="margin-left:100px;">
                                <div class="photoList">
                                  <ul>
                                    <li v-for="(item,i) in photoList">
                                      <span class="imgInfo">
                                        <span>
                                            <img :src="item.url" alt="">
                                        </span>
                                        <p class="photoInfo" :class="aciveIndex==i ? 'actives ':''" @click="handleSetPhoto(item,aciveIndex=i)"><em>{{aciveIndex==i?'商品主图':"设为主图"}}</em><em @click="handleDelPhoto(item.uid,i)">删除图片</em></p>
                                      </span>
                                       
                                    </li>
                                  </ul>
                                  <div>
                                      <el-upload
                                      class="upload-demo"
                                      ref="upload"
                                      :action="apiUrl+'/upload/native.do'"
                                      :on-success="handleFileSuccess" 
                                      :show-upload-list="false">
                                      <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
                                      
                                    </el-upload>
                                    <el-button size="small" type="primary" @click="photoSelect('1')">从图片库选择</el-button>
                                    <span class="el-upload__tip">最多可以上传5张图片，建议尺寸800*800px</span>
                                  </div>
                                </div>
                              </div>
                              <h3 class="goodTit"><i></i>详情描述</h3>
                              <div>
                                  <quill-editor v-model="content"
                                  ref="myQuillEditor"
                                  :options="editorOption"
                                  @blur="onEditorBlur($event)"
                                  @focus="onEditorFocus($event)"
                                  @ready="onEditorReady($event)">
                                </quill-editor>
                              </div>
                              
                              <!-- 从图库选择 -->
                              <el-dialog
                              title="从图库选择"
                              :visible.sync="selectVisible"
                              width="30%"
                              center>
                              <el-form ref="reference">
                              <div class="breadInfo clear">
                                <el-breadcrumb separator-class="el-icon-arrow-right">
                                    <el-breadcrumb-item>商品图库</el-breadcrumb-item>
                                    <el-breadcrumb-item>全部图片</el-breadcrumb-item>
                                </el-breadcrumb>
                                <el-select v-model="value8" filterable placeholder="请选择" @change="handleSelect" class="photo">
                                  <el-option
                                    v-for="item in imageList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                                    {{item.title}}
                                  </el-option>
                                </el-select>
                              </div>
                              <div class="imagesList">
                                <ul>
                                  <li v-for="item in imageItems">
                                    <span v-for="test in item.imageItems" class="imgInfo">
                                       <img :src="test.url" alt="">
                                       <span class="checkBox">
                                           <!-- <input type="checkbox" @click="handleCheck($event,item,test)"/> -->
                                           <el-checkbox @change="handleCheck($event,item,test)"></el-checkbox>
                                       </span>
                                    </span>
                                  </li>
                                </ul>
                                <div class="pages">
                                   <el-pagination background 
                                   @size-change="handleSizeChange" 
                                   @current-change="handleCurrentChange" 
                                   :current-page="Number(requestParameters.page)" 
                                   :total="Number(total)" 
                                   :page-size="Number(requestParameters.size)" 
                                   :page-sizes="[10,20,30, 50]" 
                                   layout="prev, pager, next" 
                                   >
                                   </el-pagination>
                               </div>
                              </div>
                              </el-form>
                               <p class="infoTip">已选中<span class="fontSize">{{imagesLength.length}}</span>张图片</p>
                              <span slot="footer" class="dialog-footer">
                                <el-button @click="selectVisible = false">取 消</el-button>
                                <el-button type="primary" @click="imgOK(selectNum)">确 定</el-button>
                              </span>
                            </el-dialog>
                            </el-form>
                          </template>
                      </div>
                      <!-- end -->
                      <div class="but-group butBox">
                          <el-button @click.native.prevent="handlePreStep" v-show="preStep" class="el-button-pre">{{this.preInfo}}</el-button>
                          <el-button @click.native.prevent="handleNextStep" v-show="nextStep" type="primary">{{this.nextInfo}}</el-button>
                      </div>
                  </div>
              </template>
            </div>
        </div>
    </div>
            
    </div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script><!-- vue -->
<script src="../js/elementui.js"></script><!-- element-ui -->
<script type="text/javascript" src="../js/axios.js"></script><!-- axios交互-->
<script type="text/javascript" src="../js/util.js"></script><!-- 公用js -->
<script type="text/javascript" src="../js/base.json"></script><!-- 公用js -->
<!-- 编辑器 -->
<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.4/quill.js"></script>
<!-- Quill JS Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js"></script>
<!-- Include stylesheet -->
<link href="../css/quill.core.css" rel="stylesheet">
<link href="../css/quill.snow.css" rel="stylesheet">
<link href="../css/quill.bubble.css" rel="stylesheet">
<script>
  Vue.use(VueQuillEditor)
var skus = [];
  // 子组件
    Vue.component('transf-item', {
      props: {
        titleId: {
          type: Number,
        },
        districtList: { // 父组件传递的区域数据
          type: Array,
        },
      },
      data () {
        return {
          title: ['选择一级分类', '选择二级分类', '选择三级分类', '选中地区'],
          districtListMock: [], // 展示的数据 （搜索会自动修改这个数组）
          checkedCities: [], // 已选择，数据格式：[区域id,id,id...]
          father: {}, // 父级数据
          buttonAble: true,
          active:-1,
          preInfo:false
        };
      },
      created () {
          this.getAlls();
        },
      watch: {
        districtList () {
          this.getAlls();
          if (this.districtList.length === 0) {
            this.checkedCities = [];
          }
        },
      },
      methods: {
        // 获取区域数据
        getAlls () {
          this.districtListMock = this.districtList;
          // 已选择的清空
          this.checkedCities = [];
        },
        // 选择
        handleCheckedChange (value,index) {
          this.active=index;
          // 子传父
          this.$emit('check-district', value);
        },
      },
        template: `
        <div class="el-transfer-panel district-panel">
            <div class="el-transfer-panel__header">
            {{title[titleId]}}
          </div>
          <div class="el-transfer-panel__body">
            <ul v-if="districtListMock.length > 0">
              <li v-for="(item,index) in districtListMock" :class="index==active?'active':''" class="el-transfer-panel__item" @click="handleCheckedChange(item,index)" :label="item" :key="item.id">
              {{item.name}}
                <i v-if="item.parentId===0" class="fa fa-angle-right" aria-hidden="true"></i>
              </li>
            </ul>
            <p class="no-data" v-else>无数据</p>
          </div>
        </div>`
    })

    new Vue({
        el: '#app',
        // router,
        data() {
            return {
                aciveIndex:'0',
                apiUrl:'',
                active:0,
                actives:'1',
                activeData:[],
                preStep: false,
                nextStep: true,
                step: 0,
                step1:true,
                step2:false,
                step3:false,
                preInfo:'',
                nextInfo:'下一步，填写商品信息',
                titInfo:'选择商品分类',
                // 第一步
                flag: false, // 分仓对应的省id变量的监听器的锁，第一次触发不执行，数据还未初始化
                classaData: [], // 一级级数据
                twoData: [], // 二级数据
                threeData: [], // 区级数据
                twoShow:false,
                threeShow:false,
                firstInfo:{
                  name:''
                },
                twoInfo:{
                  name:''
                },
                threeInfo:{
                  name:''
                },
                stepTip:null,
                // 第二步
                brandData:[],
                templateData:[],
                rules: { //表单验证
                  name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' }
                  ],
                  caption: [
                    { required: true, message: '请输入副标题', trigger: 'blur' }
                  ],
                  brandId: [
                    { required: true, message: '请选择品牌', trigger: 'change' }
                  ],
                  freightId: [
                    { required: true, message: '请选择模板', trigger: 'change' }
                  ],
                  introduction: [
                    { required: true, message: '请输入介绍信息', trigger: 'blur' }
                  ],
                  sn: [
                    { required: true, message: '请输入货号', trigger: 'blur' }
                  ]
                },
                nameInfo:'',
                serverData:base.service,
                // 第三步
                spec:'',
                ishow:null,
                addName:'',
                properties: [],
                proper:[],
                skus: skus,
                checked: true,
                disabled:false,
                vals:[],
                upVisible:false,
                photoInfo:{
                  select:1
                },
                upPhotoData:[],
                selectVisible:false,
                photoList:[],
                imageItems:[],
                imageList:[],
                photoItems:[],
                imagesLength:[],
                value8:'',
                total:null,
                requestParameters: {
                  page: 1,
                  size: 10
              },
              attachments:[],
              paraItems:[],
              paraOption:null,
              content: '请填写信息',
              editorOption: {
                  theme: 'snow'
                },
              goods:{
                "spu":{
                  name: '',// 名称
                  caption: '',// 副标题
                  brandId:'', // 品牌ID
                  category1Id:'', // 一级分类
	                category2Id: '',// 二级分类
	                category3Id: '',// 三级分类
                  introduction:'',// 商品介绍
                  freightId:'',// 运费模板
                  freight_name:'',// 运费模板
                  saleService:[], //售后服务
                  sn:'',//货号
                  specItems:[]
                },
                "skuList":[]
              },
              imagesList:[],
              imageData:[],
              parname:[],
              selectNum:'',
              imagesD:[],
              imageObj:{},
              spuImages:[],
              spuImageList:[],
              photoInfoInfo:'设为主图',
              linkId:'',
              tableDate:[]
            }
        },
        components: {
          LocalQuillEditor: VueQuillEditor.quillEditor
        },
        // 侦听器
        computed:{
          // 侦听商品规格表格的变动
            allCheckedLength:function(){
                var length=0;
                for(var i=0;i<this.properties.length;i++){
                  length+=this.properties[i].selectedValues.length;
                }
                return length;
            }

        },
        // 监测数据变动
        watch: {
          'allCheckedLength': {
              handler: 'reBuild'
          }
        },
        created () {
          this.apiUrl="" //获取服务器接口
          this.linkId = getQueryString('id')//获取列表页传过来的id
          this.getAll();
          this.getDetails() //获取详情
        },
        methods: {
          // 上一步按钮
        handlePreStep: function () {
              this.step--;
              this.goStep(this.step);
              document.body.scrollTop = document.documentElement.scrollTop = 0;
        },
        // 下一步按钮
        handleNextStep: function (e) {
            if(this.firstInfo.name!==""&&this.twoInfo.name!==""&&this.threeInfo.name!==""){
              var _this = this
              setTimeout(function() {
                _this.step++
                _this.goStep(_this.step)
              })
              }else{
                this.$message({
                showClose: true,
                message: '请选择分类',
                type: 'error'
              });
              
              }
              document.body.scrollTop = document.documentElement.scrollTop = 0;
        },
        goStep: function (n,formName) {
          switch (n) {

            case 0 :
              this.preStep = false;
              this.nextStep = true;
              this.step1=true;
              this.step2=false;
              this.step3=false
              this.nextInfo='下一步，填写商品信息'
              break;
              
            case 1 :
              this.preStep = true;
              this.nextStep = true;
              this.step1=false;
              this.step2=true;
              this.step3=false
              this.preInfo='上一步，填写商品分类'
              this.nextInfo='下一步，填写商品属性'
              
              this.getBrandData()
              this.getTemplateData()
              this.paraList() //商品参数
              // this.getPhoto() //获取商品相册
              
              break;
            case 2 :
              this.$refs.ruleForm.validate(valid => {
                if (valid) {
                  this.preStep = true;
                  this.nextStep = true;
                  this.preInfo='上一步，填写商品信息'
                  this.nextInfo='提交审核'
                  this.titInfo='下一步，填写商品属性'
                  this.step1=false;
                  this.step2=false;
                  this.step3=true
                  this.nameInfo=this.goods.spu.name
                  this.goods.spu.freightId=this.goods.spu.freightId
                  // if(this.linkId!==null){
                  var data=[]
                  var obj={}
                  // 规格默认列表
                  for(var i=0;i<this.tableDate.length;i++){
                    this.tableDate[i].spec=JSON.parse(this.tableDate[i].spec)
                    data.push(this.tableDate[i].spec)
                  }
                    
                    for(var k=0;k<data.length;k++){
                      for(var i in data[k]){
                        // console.log(this.proper)
                          for(var n=0; n<this.proper.length;n++){
                            if(i==this.proper[n].name){
                              var obj={
                                Id: k,
                                PropertyId: this.proper[n].id,
                                PropertyName: this.proper[n].name,
                                name: data[k][i]
                              }
                              this.proper[n].selectedValues.push(obj)

                            }
                          }
                      };
                      
                    }
                  // }
                  // 过规格默认选项
                  let newArr =[]
                  for(var k=0;k<data.length;k++){
                      for(let item in data[k]){
                        newArr[item]=[]
                    }
                  };
                  data.map(function(n,i){
                    for(let it in n){
                      newArr[it].push(n[it])
                    }
                  })
                  for(var p=0;p<this.properties.length;p++){
                    this.$set(this.properties[p], 'select', [])
                    for(a in newArr){
                      if(a==this.properties[p].name){
                        this.properties[p].selectedValues=unique1(newArr[a])
                      }
                    }
                  }

                } else {
                  this.stepTip=false
                  console.log('error submit!!');
                  return false;
                }
                });          
              break;
            case 3 :
              this.preStep = true;
              this.nextStep = true;
              this.preInfo='上一步，填写商品信息'
              this.nextInfo='提交审核'
              this.titInfo='下一步，填写商品属性'
              // 获取spu图片
              
              for(var n=0;n<this.photoList.length;n++){
                  this.spuImages.push(this.photoList[n].image)
                  this.spuImageList.push(this.photoList[n].url)
                  // for(var k=0;k<this.photoList[n].imageItems.length;k++){
                  //   this.spuImageList.push(this.photoList[n].imageItems[k].url)
                  // }
              }
              this.goods.spu.image=this.spuImageList[0]
              this.goods.spu.images=this.spuImageList.join(',')
              // this.goods.spu.image=this.photoList
              // this.goods.spu.images=this.photoList
              // 处理服务保证
              this.goods.spu.saleService=(this.goods.spu.saleService).join(',')
              // 处理详情描述
              this.goods.spu.introduction=this.$refs.myQuillEditor.quill.container.firstChild.innerHTML
              // 判断是否编辑

              if(this.linkId!==null){
                axios.post(this.apiUrl+`/spu/save.do?id=${this.linkId}`,this.goods).then(response => {})
              }else{
                axios.post(this.apiUrl+`/spu/save.do`,this.goods).then(response => {                  
				  //if(response.code==0){				  
					alert('成功');
					window.location.href="goods_edit.html"
				  //}else{
					//alert(JSON.stringify(response));
				  //}
                  console.log(response)
                })
              }
              
              break;
          }
        },
        //**********************第一步**********************
        // 获取列表详情
        getDetails(){
          var _this=this
          if(this.linkId!==null){
            axios.get(this.apiUrl+`/spu/findGoodsById.do?id=${this.linkId}`).then(response => {
              this.goods.spu=response.data.spu
              this.tableDate=response.data.skuList
              this.content=this.goods.spu.introduction
              if(response.data.spu.saleService!==null){
                this.goods.spu.saleService=response.data.spu.saleService.split(",")
              }
              
              if(this.goods.spu.category1Id!==""||this.goods.spu.category2Id!==""||this.goods.spu.category3Id!==""){
                this.twoShow=true
                this.threeShow=true
                var data=[]  
                // 获取一级菜单
                axios.post(this.apiUrl+`/category/findList.do`,{'parentId':0}).then(response => {
                  this.classaData=response.data
                  // 当前选择的一级类别
                  for(var i=0;i<this.classaData.length;i++){
                    if(this.goods.spu.category1Id==this.classaData[i].id){
                      this.firstInfo.name=this.classaData[i].name+">"
                      data.push(i)
                      this.activeData=data
                    }
                   }
                })
                // 获取二级菜单
                axios.post(this.apiUrl+`/category/findList.do`,{'parentId':this.goods.spu.category1Id}).then(response => {
                  this.twoData=response.data
                  // 当前选择的二级类别
                  for(var i=0;i<this.twoData.length;i++){
                    if(this.goods.spu.category2Id==this.twoData[i].id){
                      this.twoInfo.name=this.twoData[i].name+">"
                      data.push(i)
                    }
                  }
                })
                // 获取三级菜单
                axios.post(this.apiUrl+`/category/findList.do`,{'parentId':this.goods.spu.category2Id}).then(response => {
                  this.threeData=response.data
                  // 当前选择的三级类别
                  for(var i=0;i<this.threeData.length;i++){
                    if(this.goods.spu.category3Id==this.threeData[i].id){
                      this.threeInfo.name=this.threeData[i].name
                      data.push(i)
                    }
                  }
                })
                
              }
              this.getParameterData(response.data.spu.freightId)
            })
          }
        },
        // 获取数据
        getAll() {
          // 从后台传回经过处理的数据
          this.flag = true; // 数据加载完成，解锁
          this.handleClassA();
        },
        // 获取一级数据
        handleClassA () {
          this.classaData = []; // 首先清空
          axios.post(this.apiUrl+`/category/findList.do`,{'parentId':0}).then(response => {
            this.classaData=response.data
            this.preInfo=true
            })
            
        },
        // 获取二级数据，子组件自定义的穿梭框传回的数据，val：[区域obj, 区域obj,...]
        handleclassType(val) {
          this.firstInfo={
              name:val.name
          }
          this.goods.spu.category1Id=val.id
          let flag = true;
          if (val !== undefined) {
            axios.post(this.apiUrl+`/category/findList.do`,{'parentId':val.id}).then(response => {
              this.twoData=response.data
              if(this.linkId!==null){

              }else{
                if(this.twoData.length>0){
                  this.twoShow=true
                  this.threeShow=false
                }else{
                  this.twoShow=false
                  this.threeShow=false
                }
                // 再清空上一次的数据
                this.threeData = [];
                // 将父级对象放进组件
                this.$refs.twoType.father = {
                  id: val.id,
                  name: val.name,
                };
                flag = false;
              }
              
            })
          }
          // 如果没有匹配到，都显示为空
          if (flag) {
            this.twoData = [];
            this.threeData = [];
          }
        },
        // 获取三级数据，子组件自定义的穿梭框传回的数据，val：[区域obj, 区域obj,...]
        handleTwoType (val) {
          this.twoInfo={
              name:'>'+val.name
          }
          this.goods.spu.category2Id=val.id
          let flag = true;
          if (val !== undefined) {
            axios.post(this.apiUrl+`/category/findList.do`,{'parentId':val.id}).then(response => {
              this.threeData=response.data
              if(this.threeData.length>0){
                  this.threeShow=true
                }else{
                  this.threeShow=false
                }
                // 获取数据
                let fatherId = this.$refs.twoType.father.id;
                let fatherText = this.$refs.twoType.father.name;
                this.$refs.threeType.father = {
                  id: fatherId + '-' + val.id,
                  name: fatherText + '-' + val.name,
                };
                flag = false;
            })
          }
          // 区级没有匹配到，显示为空
          if (flag) {
            this.threeData = [];
          }
        },
        // 获取三级数据
        handleThreeType(val){
          this.threeInfo={
              name:'>'+val.name
          }
          this.goods.spu.category3Id=val.id
        },
        //**********************第二步**********************
        handleEdit(){
          this.step--;
          this.goStep(this.step);
        },
        // 商品品牌
        getBrandData(formName) {
          axios.get(this.apiUrl+`/brand/findAll.do`).then(response => {
              this.brandData=response.data
            })
        },
        // 运费模板
        getTemplateData(formName) {
          axios.get(this.apiUrl+`/template/findAll.do`).then(response => {
              this.templateData=response.data
            })
        },
        // 获取参数
        getParameterData(id) {
          
          axios.post(this.apiUrl+`/spec/findList.do`,{"templateId":id}).then(response => {
            var activeSubjectsName
            var obj=[]
            var data={}
              for(var i=0;i<response.data.length;i++)
              { 
                obj.push({
                  name:response.data[i].name,
                  options:response.data[i].options
                })
                this.$set(response.data[i], 'selectedValues', [])
                this.$set(response.data[i], 'spec', {})
                response.data[i].options = (response.data[i].options).split(',')
              }
              this.properties=response.data
              for(var i=0;i<obj.length;i++){
                data[obj[i].name]=obj[i].options.split(',');
              }
              // 获取商品属性列表
              this.goods.spu.specItems=data
              this.properties=response.data
              this.proper=response.data
            })  
        },
        // 选择模板数据
        handleChange(val){
          let obj = {};
          obj = this.templateData.find((item)=>{//templateData是上面遍历的数据
              return item.id === val;//筛选出匹配数据
          });
          // this.goods.spu.freight_name=obj.name
          this.getParameterData(obj.id)
        },
        // 规格添加
        handleAdd(name,num){
          for(var i=0;i<this.properties.length;i++){
            if(this.properties[i].id===num){
              this.properties[i].options.push(name)
            axios.post(this.apiUrl+`/spec/add.do`,{"spec":name}).then(response => {
              
            })
            }      
          }  
        },
        dataDetails(index){
          this.ishow = index
        },
        // 删除商品规格
        handleDel(nameId,id){
          this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
            type: 'warning'
          })
            .then(() => {
              axios.get(this.apiUrl+`/spec/delete.do?id=${id}`).then(response => {
                this.$message.success('删除成功' + '!')
                for(var i=0;i<this.properties.length;i++){
                  if(this.properties[i].id===nameId){
                    
                    (this.properties[i].options).splice(id,1)
                  }
                }
              })
                .catch(response => {
                  this.$message.error('删除失败!')
                })
            })
            .catch(() => {
              this.$message.info('已取消操作!')
            })
        },
        descartes(list)
        {
            //parent上一级索引;count指针计数
            var point = {};
            var result = [];
            var pIndex = null;
            var tempCount = 0;
            var temp  = [];
            //根据参数列生成指针对象
            for(var index in list)
            {
                if(typeof list[index] == 'object')
                {
                    point[index] = {'parent':pIndex,'count':0}
                    pIndex = index;
                }
            }
            //单维度数据结构直接返回
            if(pIndex == null)
            {
                return list;
            }
            //动态生成笛卡尔积
            while(true)
            {
                for(var index in list)
                {
                    tempCount = point[index]['count'];
                    temp.push(list[index][tempCount]);
                }
                //压入结果数组
                result.push(temp);
                temp = [];
                //检查指针最大值问题
                while(true)
                {
                    if(point[index]['count']+1 >= list[index].length)
                    {
                        point[index]['count'] = 0;
                        pIndex = point[index]['parent'];
                        if(pIndex == null)
                        {
                            return result;
                        }
                        //赋值parent进行再次检查
                        index = pIndex;
                    }
                    else
                    {
                        point[index]['count']++;
                        break;
                    }
                }
            }
        },
        // 
        reBuild: function (val, oldVal) {
          var vm=this;
                var vmSkus = this.skus = [];
                var ori = [];
                var data
                var sku
                // var datas={alertNum: "", price: "", num: "","sn": "","data": data,image:{},images:{}};
                for(var i=0;i<vm.properties.length;i++){
                  var selectValues = vm.properties[i].selectedValues;
                  if (selectValues.length > 0) {
                    data=vm.properties[i]
                    ori.push(selectValues);
                  }
                }
                var ret = this.descartes(ori);
                for (var i = 0; i < ret.length; i++) {
                  var obj={ }
                  if(this.linkId!==null){
                    if(this.tableDate.length>0){
                      for(var k=0;k<this.tableDate.length;k++){
                        var sku = {
                          alertNum: this.tableDate[k].alertNum, 
                          price: this.tableDate[k].price, 
                          num: this.tableDate[k].num,
                          sn:this.tableDate[k].sn,
                          weight:this.tableDate[k].weight,
                          status:this.tableDate[k].status,
                          // spec:obj,
                          image:this.tableDate[k].image,
                          images:this.tableDate[k].images
                          };
                          
                      }
                    }else{
                      sku = {alertNum: "", price: "", num: "","sn": "","data": data,image:{},images:{}};
                    }
                  }else{
                    sku = {alertNum: "", price: "", num: "","sn": "","data": data,image:{},images:{}};
                  }
                  this.$set(sku, 'options', [])
                  for(k in this.properties){
                    for(n in this.properties[k].options){
                      for(var o=0;o<ret[i].length;o++){

                        if(ret[i][o]==this.properties[k].options[n]){
                          sku.options.push({
                          propertyId: this.properties[k].id,
                          PropertyName:this.properties[k].name, 
                          name: ret[i][o]
                        })
                        sku.spec=sku.options
                        sku.spec.map(function(e){
                          obj[e.PropertyName] = e.name;
                        })
                        sku.spec=obj
                        } 
                    }
                  }
                  }
                  vmSkus.push(sku); 
                }
                this.tableDate=vmSkus
                // console.log(this.tableDate)
                this.goods.skuList=this.tableDate
            },
            // 上传图片获取imges数据
            handleUpPhoto(){
              for(var i=0;i<this.tableDate.length;i++){
                if(this.tableId==i){
                var obj=""
                var objImage=""
                this.imagesList.map(function(e){
                  var dataImage=[]
                  dataImage.push(e.image)
                  objImage=dataImage.join(",")
                  var data=[]
                  e.imageItems.map(function(n){
                  data.push(n.url)
                  })
                  obj= data.join(",");
                })
                this.tableDate[i].images=obj
                this.tableDate[i].image=objImage
                this.upVisible=false
                }
              }
            },
            // 获取上传图片商品信息
            handleUpdate(index,val){
              this.tableId=index
              this.upVisible=true
              this.upPhotoData=val.options
            this.getListPage()
            },
            // 图库选择
            photoSelect(num){
              this.selectVisible=true
              this.selectNum=num
              this.getListPage()
            },
            // 上传图片成功
            handleFileSuccess(res, file) {
              this.attachments.push(file.response)
            },
            // 选中图片
            handleCheck(e,item,test){
              if(e==true){
                this.imagesLength.push(item.url)
                for(var i=0;i<item.imageItems.length;i++){
                  if(test.uid==item.imageItems[i].uid){
                    this.imagesD.push(test)
                    this.imageObj={
                    id:item.id,
                    image:item.image,
                    imageItems:this.imagesD,
                    title:item.title
                  }
                    this.imagesList=[this.imageObj]
                  }
                }
              }
              if(e==false){
                for(var k=0;k<this.imagesList.length;k++){
                  for(var n=0;n<this.imagesList[k].imageItems.length;n++){
                    if(test.uid==this.imagesList[k].imageItems[n].uid){
                    this.imagesList[k].imageItems.splice(n,1)
                  }
                  }
                }
                this.imagesLength.splice(0, 1)
              }
            },
            // 筛选图片
            handleSelect(val){
              
              for(var i=0;i<this.imageItems.length;i++){
                axios.get(this.apiUrl+`/album/findById.do?id=${val}`).then(response => {
                    response.data.imageItems =  JSON.parse(response.data.imageItems)
                    this.imagesLength=[]
                    this.imageItems=[]
                    this.imageItems.push(response.data)
                })
              }
            },
            // 筛选图片分页
            getListPage(){  
              axios.get(this.apiUrl+`/album/findPage.do?page=${this.requestParameters.page}&size=${this.requestParameters.size}`).then(response => {
                this.total=response.data.total
                  for(var i=0;i<response.data.rows.length;i++){
                    response.data.rows[i].imageItems =  JSON.parse(response.data.rows[i].imageItems)
                  }
                  this.imageItems=response.data.rows
                  this.imageList=response.data.rows
                })
            },
            // 获取商品相册
            getPhoto(){
              axios.get(this.apiUrl+`/album/findAll.do`).then(response => {
                  for(var i=0;i<response.data.length;i++){
                    response.data[i].imageItems =  JSON.parse(response.data[i].imageItems)
                  }
                  this.photoItems=response.data
                })
            },
            // 每页显示信息条数
            handleSizeChange(val) {
              this.requestParameters.size = val
              if (this.requestParameters.page === 1) {
                this.getListPage(this.requestParameters)
              }
            },
            // 进入某一页
            handleCurrentChange(val) {
              this.requestParameters.page = val
              this.getListPage()
            },
            // 商品参数
            paraList(){
              axios.get(this.apiUrl+`/para/findAll.do`).then(response => {
                for(var i=0;i<response.data.length;i++){
                  response.data[i].options=response.data[i].options.split(',')
                } 
                this.paraItems=response.data
                if(this.linkId!==null){
                  var obj={}
                  obj=JSON.parse(this.goods.spu.paraItems)
                  for (let i in obj) {
                        for(var n in this.paraItems){
                          if(i==this.paraItems[n].name){
                            this.paraItems[n].city=obj[i]
                          } 
                        }
                    }
                }
                })
            },
            // 
            handleSetPhoto(item){
              this.goods.spu.image=item.url
            },
            // 商品相册删除某一张
            handleDelPhoto(Id,index){
              this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
                type: 'warning'
              })
                .then(() => {
                  this.photoList.splice(index,1)
                })
                .catch(() => {
                  this.$message.info('已取消操作!')
                })
            },
            onEditorBlur(quill) {
              console.log('editor blur!', quill)
            },
            onEditorFocus(quill) {
              console.log('editor focus!', quill)
            },
            onEditorReady(quill) {
              console.log('editor ready!', quill)
            },
            // 从图库选择图片
            imgOK(formName){
                if(this.photoItems.length>5){
                this.$message.error('最多只能上传5张')
                  return false
                }else if(this.imagesLength.length===0){
                  this.$message.error('请选择图片')
                  return false
                }else{
                  if(formName==='1'){
                    this.photoList=this.imageObj.imageItems
                  }
                  
                  this.selectVisible=false
                }
              
            },
            // 商品参数
            handlePara(handlePara){
              var data=[]
              for(var i=0;i<this.paraItems.length;i++){
                if(handlePara.id===this.paraItems[i].id){
                  this.parname.push(handlePara)
                }
              }
              var obj={ };
              this.parname.map(function (e, item) {
                obj[e.name] = e.city;
              });
            this.goods.spu.paraItems=obj
            },
            // 输入数字 不可小数
            handleNumber(e) {
              // log(e.target.value)
              e.target.value=e.target.value.replace(/[^\d]/g,'');
            },
            
      }
    })
 
</script>
</html>
